﻿using System.Security.Principal;
using System.Web;
using IterationLife.Datas;
using IterationLife.System.Repositories;
using Microsoft.Ajax.Utilities;
using Util;
using Util.Domains.Contexts;
using Util.Helpers;
using Util.Security;
using Util.Webs.Security;
using Util.Iocs;

namespace IterationLife.PlatformBackEnd.WebSite.Authentication
{
    /// <summary>
    /// 身份认证模块
    /// </summary>
    public class AuthenticationModule : AuthenticateModuleBase
    {
        private IUserRepository _userRepository;

        protected override bool AuthenticateBefore(HttpApplication application)
        {
            base.AuthenticateBefore(application);
            _userRepository = Ioc.Create<IUserRepository>();
            return true;
        }

        /// <summary>
        /// 创建应用程序上下文
        /// </summary>
        /// <param name="userId">用户编号</param>
        protected override IUserContext CreateUserContext(string userId)
        {
            if (userId.IsEmpty())
                return NullUserContext.Instance;
            UserContext result = new UserContext(true, userId, Net.Ip, Net.Host, Net.Browser);
            SetUser(result, userId);
            result.SetApplication(applicationId: string.Empty, applicationName: "迭代生活平台后台管理系统");
            return result;
        }

        /// <summary>
        /// 设置用户
        /// </summary>
        private void SetUser(UserContext context, string userId)
        {
            var user = _userRepository.Find(userId.ToGuid());
            context.SetUser(user.UserName, user.Email, user.Mobile);
        }

    }
}
